package com.example.zjsr.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.zjsr.common.ServerResponse;
import com.example.zjsr.domain.Admin.anchors.Anchors;
import com.example.zjsr.domain.Admin.anchors.Trait;
import com.example.zjsr.domain.Admin.knowledge.HeadLine;
import com.example.zjsr.domain.Admin.knowledge.Knowledge;
import com.example.zjsr.domain.Admin.knowledge.KnowledgeAnswer;
import com.example.zjsr.domain.Admin.platform.Platform;
import com.example.zjsr.domain.Admin.platform.PlatformBo;
import com.example.zjsr.domain.User;
import com.example.zjsr.service.AnchorsService;
import com.example.zjsr.service.KnowledgeService;
import com.example.zjsr.service.PlatformService;
import com.example.zjsr.util.EmptyUtil;
import com.example.zjsr.util.ExcelUtils;
import com.example.zjsr.util.JwtUtil;
import com.example.zjsr.util.RedisUtil;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.parameters.P;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * @author lvyongwei
 * @description 此内容是最后添加的管理内容，管理部分内容，并将前端写死的内容动态给他
 *             部分内容是基于之前已有内容
 */
@RestController
@CrossOrigin
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private KnowledgeService knowledgeService;

    @Autowired
    private AnchorsService anchorsService;

    @Autowired
    private PlatformService platformService;
    /**
     * 修改问题及答案内容
     * @param knowledge
     * @param request
     * @return
     */
    @PostMapping("/updateKnowledge")
    public ServerResponse<String> updateKnowledge(@RequestBody Knowledge knowledge, HttpServletRequest request){
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ")+1);
        User u = JwtUtil.unsign(jwt,User.class);
        if(u == null){
            return ServerResponse.createByErrorMsg("token无效");
        }
/*        if(!jwt.equals(redisUtil.get(u.getId()+""))){
            return ServerResponse.createByAuthMsg("该账号已经在别处登录！");
        }*/
        try{
            knowledgeService.updateKnowledge(knowledge);
            return ServerResponse.createBySuccess("修改问题成功!");
        }catch (Exception e){
            e.printStackTrace();
            return ServerResponse.createByACCOUNTError("修改问题失败!");
        }
    }

    /**
     * 查询所有问题
     * @param data
     * @param request
     * @return
     */
    @PostMapping("/selectKnowledge")
    public ServerResponse<Object> selectKnowledge(@RequestBody String data,HttpServletRequest request){
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ")+1);
        User u = JwtUtil.unsign(jwt,User.class);
        if(u == null){
            return ServerResponse.createByErrorMsg("token无效");
        }
/*        if(!jwt.equals(redisUtil.get(u.getId()+""))){
            return ServerResponse.createByAuthMsg("该账号已经在别处登录！");
        }*/
        JSONObject jsonObject = JSONObject.parseObject(data);
        Integer headLineId = jsonObject.getInteger("headLineId");
        try{
            List<Knowledge> knowledges = knowledgeService.selectKnowledge(headLineId);
            return ServerResponse.createBySuccess("获取内容成功",knowledges);
        }catch (Exception e){
            return ServerResponse.createByACCOUNTError("获取内容失败");
        }
    }

    /**
     * 根据问题id查询所有答案
     * @param data
     * @param request
     * @return
     */
    @PostMapping("/selectKnowledgeAnswer")
    public ServerResponse<Object> selectKnowledgeAnswer(@RequestBody String data,HttpServletRequest request){
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ")+1);
        User u = JwtUtil.unsign(jwt,User.class);
        if(u == null){
            return ServerResponse.createByErrorMsg("token无效");
        }
/*        if(!jwt.equals(redisUtil.get(u.getId()+""))){
            return ServerResponse.createByAuthMsg("该账号已经在别处登录！");
        }*/
        JSONObject jsonObject = JSONObject.parseObject(data);
        Integer knowledgeId = jsonObject.getInteger("knowledgeId");
        try{
            List<KnowledgeAnswer> knowledgeAnswers = knowledgeService.selectKnowledgeAnswer(knowledgeId);
            return ServerResponse.createBySuccess("获取内容成功",knowledgeAnswers);
        }catch (Exception e){
            return ServerResponse.createByACCOUNTError("获取内容失败");
        }
    }

    /**
     * 提供给前端实验时使用(所有知识互动以及所属分组并包含其答案)
     * @return
     */
    @PostMapping("/selectAllKnowledge")
    public ServerResponse<List<HeadLine>> selectAllKnowledge(HttpServletRequest request){
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ")+1);
        User u = JwtUtil.unsign(jwt,User.class);
        if(u == null){
            return ServerResponse.createByErrorMsg("token无效");
        }
/*        if(!jwt.equals(redisUtil.get(u.getId()+""))){
            return ServerResponse.createByAuthMsg("该账号已经在别处登录！");
        }*/
        try{
            List<HeadLine> headLines = knowledgeService.selectAllKnowledge();
            return ServerResponse.createBySuccess("获取内容成功",headLines);
        }catch (Exception e){
            return ServerResponse.createByACCOUNTError("获取内容失败");
        }
    }

    /**
     * 查询所有主播信息
     * @param pageNum
     * @param pageSize
     * @param request
     * @return
     */
    @GetMapping("/selectAnchors")
    public ServerResponse<PageInfo<Anchors>> selectAnchors(@RequestParam(defaultValue = "1",required = false) Integer pageNum,
                                                       @RequestParam(defaultValue = "10",required = false)Integer pageSize,
                                                       HttpServletRequest request){
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ")+1);
        User u = JwtUtil.unsign(jwt,User.class);
        if(u == null){
            return ServerResponse.createByErrorMsg("token无效");
        }
/*        if(!jwt.equals(redisUtil.get(u.getId()+""))){
            return ServerResponse.createByAuthMsg("该账号已经在别处登录！");
        }*/
        try{
            PageInfo<Anchors> pageInfo = anchorsService.selectAnchors(pageNum, pageSize);
            return ServerResponse.createBySuccess("获取内容成功",pageInfo);
        }catch (Exception e){
            e.printStackTrace();
            return ServerResponse.createByACCOUNTError("获取内容失败");
        }
    }

    /**
     * 查询所有特点信息
     * @param request
     * @return
     */
    @GetMapping("/selectTraits")
    public ServerResponse<List<Trait>> selectTraits(HttpServletRequest request){
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ")+1);
        User u = JwtUtil.unsign(jwt,User.class);
        if(u == null){
            return ServerResponse.createByErrorMsg("token无效");
        }
/*        if(!jwt.equals(redisUtil.get(u.getId()+""))){
            return ServerResponse.createByAuthMsg("该账号已经在别处登录！");
        }*/
        try{
            List<Trait> traits = anchorsService.selectTraits();
            return ServerResponse.createBySuccess("获取内容成功",traits);
        }catch (Exception e){
            return ServerResponse.createByACCOUNTError("获取内容失败");
        }
    }

    /**
     * 添加特点信息
     * @param trait
     * @param request
     * @return
     */
    @PostMapping("/insertTrait")
    public ServerResponse<String> insertTrait(@RequestBody Trait trait,HttpServletRequest request){
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ")+1);
        User u = JwtUtil.unsign(jwt,User.class);
        if(u == null){
            return ServerResponse.createByErrorMsg("token无效");
        }
/*        if(!jwt.equals(redisUtil.get(u.getId()+""))){
            return ServerResponse.createByAuthMsg("该账号已经在别处登录！");
        }*/
        try{
            Trait trait1 = anchorsService.selectByName(trait);
            System.out.println(trait1);
            if(trait1!=null){
                return ServerResponse.createByACCOUNTError("不能重复添加特点");
            }else{
                anchorsService.insertTraits(trait);
                return ServerResponse.createBySuccessMsg("添加成功");
            }
        }catch (Exception e){
            e.printStackTrace();
            return ServerResponse.createByACCOUNTError("添加失败");
        }
    }

    /**
     * 修改特点信息
     * @param trait
     * @param request
     * @return
     */
    @PostMapping("/updateTrait")
    public ServerResponse<String> updateTrait(@RequestBody Trait trait,HttpServletRequest request){
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ")+1);
        User u = JwtUtil.unsign(jwt,User.class);
        if(u == null){
            return ServerResponse.createByErrorMsg("token无效");
        }
/*        if(!jwt.equals(redisUtil.get(u.getId()+""))){
            return ServerResponse.createByAuthMsg("该账号已经在别处登录！");
        }*/
        try{
            anchorsService.updateTraits(trait);
            return ServerResponse.createBySuccessMsg("修改成功");
        }catch (Exception e){
            return ServerResponse.createByACCOUNTError("修改失败");
        }
    }

    /**
     * 删除特点信息
     * @param data
     * @param request
     * @return
     */
    @PostMapping("/deleteTrait")
    public ServerResponse<String> deleteTrait(@RequestBody String data,HttpServletRequest request){
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ")+1);
        User u = JwtUtil.unsign(jwt,User.class);
        if(u == null){
            return ServerResponse.createByErrorMsg("token无效");
        }
/*        if(!jwt.equals(redisUtil.get(u.getId()+""))){
            return ServerResponse.createByAuthMsg("该账号已经在别处登录！");
        }*/
        try{
            JSONObject jsonObject = JSONObject.parseObject(data);
            String ids = jsonObject.getString("traitIds");
            System.out.println(data);
            String[] array = ids.substring(1,ids.length()-1).split(",");
            List<Integer> traitIds = new ArrayList<>();
            for(String a:array){
                traitIds.add(Integer.valueOf(a));
            }
            anchorsService.deleteTraits(traitIds);
            return ServerResponse.createBySuccessMsg("删除成功");
        }catch (Exception e){
            e.printStackTrace();
            return ServerResponse.createByACCOUNTError("删除失败");
        }
    }

    /**
     * 修改主播达人的特点
     * @param anchors
     * @param request
     * @return
     */
    @PostMapping("/updateAnchors")
    public ServerResponse<String> updateAnchors(@RequestBody Anchors anchors,
                                                HttpServletRequest request){
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ")+1);
        User u = JwtUtil.unsign(jwt,User.class);
        if(u == null){
            return ServerResponse.createByErrorMsg("token无效");
        }
/*        if(!jwt.equals(redisUtil.get(u.getId()+""))){
            return ServerResponse.createByAuthMsg("该账号已经在别处登录！");
        }*/
        try{
            anchorsService.updateAnchorsTrait(anchors.getAnchorId(),anchors.getTraits());
            return ServerResponse.createBySuccess("修改主播达人特点成功");
        }catch (Exception e){
            return ServerResponse.createByACCOUNTError("修改主播达人特点失败");
        }
    }

    /**
     * 导出直播达人模板
     * @param response
     * @return
     */
    @GetMapping("/exportTemplate")
    public void updateAnchors(HttpServletResponse response){
        ServletOutputStream sos = null;
        try{
            Anchors anchors = new Anchors("薇娅viya","1496万+","18.3亿+","淘宝","https://v.qq.com/x/page/l09721bre23.html");
            List<Anchors> anchorsList = new ArrayList<>();
            anchorsList.add(anchors);
            sos = response.getOutputStream();
            response.setContentType("multipart/form-data");
            response.setCharacterEncoding("utf-8");
            String fileName = "主播达人信息模板";
            response.setHeader("Content-disposition", "attachment;filename="+ URLEncoder.encode(fileName,"UTF-8")+".xlsx");
            ExcelUtils.writeExcel(sos, Anchors.class,anchorsList);
            sos.flush();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (sos != null){
                try {
                    sos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 上传所有主播信息
     * @param file
     * @param request
     * @return
     */
    @PostMapping(value = "/importAuthors")
    public ServerResponse<String> leadAnchors(MultipartFile file, HttpServletRequest request){
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ")+1);
        User u = JwtUtil.unsign(jwt,User.class);
/*        if(!jwt.equals(redisUtil.get(u.getId()+""))){
            return ServerResponse.createByAuthMsg("该账号已经在别处登录！");
        }*/
        if(u == null){
            return ServerResponse.createByErrorMsg("token无效");
        }
        String fileName = file.getOriginalFilename();
        // 获取文件的后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        //创建一个临时文件，用于暂时存放
        List<Anchors> anchorsList = new ArrayList<>();
        File tmpFile = null;
        try {
            tmpFile = File.createTempFile("tmp", null);
            //将MultipartFile 转换为 File 临时文件
            file.transferTo(tmpFile);
            //将临时文件转为输入流
            InputStream inputStream = new FileInputStream(tmpFile);
            List<Object> objectList = ExcelUtils.readExcel(inputStream, Anchors.class);
            if (objectList == null) {
                return ServerResponse.createByACCOUNTError("数据有误，上传失败");
            } else if (EmptyUtil.isEmpty(objectList)) {
                return ServerResponse.createByACCOUNTError("数据为空");
            } else {
                for (int i = 0; i < objectList.size(); i++) {
                    Anchors  anchors= (Anchors) objectList.get(i);
                    anchorsList.add(anchors);
                }
                //上传完成 删除临时文件
                tmpFile.delete();
            }
            anchorsService.insertAnchors(anchorsList);
            return ServerResponse.createBySuccessMsg("上传成功");
        } catch (Exception e) {
            e.printStackTrace();
            return ServerResponse.createByACCOUNTError("上传失败");
        }
    }

    /**
     * 添加平台信息
     * @param files
     * @param request
     * @return
     */
    @PostMapping(value = "/insertPlatform")
    public ServerResponse<String> insertPlatform(Platform platform, MultipartFile[] files, HttpServletRequest request){
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ")+1);
        User u = JwtUtil.unsign(jwt,User.class);
/*        if(!jwt.equals(redisUtil.get(u.getId()+""))){
            return ServerResponse.createByAuthMsg("该账号已经在别处登录！");
        }*/
        if(u == null){
            return ServerResponse.createByErrorMsg("token无效");
        }
        try{
            platformService.insertPlatform(platform,files);
            return ServerResponse.createBySuccessMsg("添加成功！");
        }catch (Exception e){
            e.printStackTrace();
            return ServerResponse.createByACCOUNTError("添加失败！");
        }
    }

    /**
     * 修改平台基本信息
     * @param file1
     * @param file2
     * @param request
     * @return
     */
    @PostMapping(value = "/updatePlatform")
    public ServerResponse<String> updatePlatform(Platform platform,@RequestParam(required = false) MultipartFile file1,@RequestParam(required = false) MultipartFile file2, HttpServletRequest request){
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ")+1);
        User u = JwtUtil.unsign(jwt,User.class);
/*        if(!jwt.equals(redisUtil.get(u.getId()+""))){
            return ServerResponse.createByAuthMsg("该账号已经在别处登录！");
        }*/
        if(u == null){
            return ServerResponse.createByErrorMsg("token无效");
        }
        try{
            platformService.updatePlatform(platform,file1,file2);
            return ServerResponse.createBySuccessMsg("修改成功！");
        }catch (Exception e){
            e.printStackTrace();
            return ServerResponse.createByACCOUNTError("修改失败！");
        }
    }

    /**
     * 获取平台基本信息
     * @param request
     * @return
     */
    @PostMapping(value = "/getPlatforms")
    public ServerResponse<Object> getPlatforms(HttpServletRequest request){
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ")+1);
        User u = JwtUtil.unsign(jwt,User.class);
/*        if(!jwt.equals(redisUtil.get(u.getId()+""))){
            return ServerResponse.createByAuthMsg("该账号已经在别处登录！");
        }*/
        if(u == null){
            return ServerResponse.createByErrorMsg("token无效");
        }
        try{
            List<Platform> platforms = platformService.getPlatforms();
            return ServerResponse.createBySuccess("获取内容成功!",platforms);
        }catch (Exception e){
            e.printStackTrace();
            return ServerResponse.createByACCOUNTError("获取内容失败！");
        }
    }

    /**
     * 获取各个平台信息及问题等
     * @param request
     * @return
     */
    @PostMapping("/getPlatformsDetails")
    public ServerResponse<Object> getPlatformsDetails(HttpServletRequest request){
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ")+1);
        User u = JwtUtil.unsign(jwt,User.class);
/*        if(!jwt.equals(redisUtil.get(u.getId()+""))){
            return ServerResponse.createByAuthMsg("该账号已经在别处登录！");
        }*/
        if(u == null){
            return ServerResponse.createByErrorMsg("token无效");
        }
        try{
            JSONObject jsonObject = new JSONObject();
            List<Platform> platforms = platformService.getPlatforms();
            jsonObject.put("platforms",platforms);
            /**
             * 返回具体的信息
             */
            PlatformBo platformBo = new PlatformBo();
            platforms.forEach(
                    platform -> {
                        if(platform.getUserCategory()!=null && !platformBo.getUserCategories().contains(platform.getUserCategory())){
                            platformBo.getUserCategories().add(platform.getUserCategory());
                        }
                        if(platform.getDevelopmentPhase()!=null && !platformBo.getDevelopmentPhases().contains(platform.getDevelopmentPhase())){
                            platformBo.getDevelopmentPhases().add(platform.getDevelopmentPhase());
                        }
                        if(platform.getCoreGene() !=null && !platformBo.getCoreGenes().contains(platform.getCoreGene())){
                            platformBo.getCoreGenes().add(platform.getCoreGene());
                        }
                        if(platform.getCategory() !=null && !platformBo.getCategories().contains(platform.getCategory())){
                            platformBo.getCategories().add(platform.getCategory());
                        }
                        if(platform.getBrand()!=null && !platformBo.getBrands().contains(platform.getBrand())){
                            platformBo.getBrands().add(platform.getBrand());
                        }
                        if(platform.getPrice()!=null && !platformBo.getPrices().contains(platform.getPrice())){
                            platformBo.getPrices().add(platform.getPrice());
                        }
                        if(platform.getLiveStyle()!=null && !platformBo.getLiveStyles().contains(platform.getLiveStyle())){
                            platformBo.getLiveStyles().add(platform.getLiveStyle());
                        }
                    }
            );
            jsonObject.put("platformBo",platformBo);
            return ServerResponse.createBySuccess("获取内容成功！",jsonObject);
        }catch (Exception e){
            e.printStackTrace();
            return ServerResponse.createByACCOUNTError("获取内容失败！");
        }
    }

    /**
     * 修改平台基本信息
     * @param request
     * @return
     */
    @PostMapping(value = "/updatePlatformDetail")
    public ServerResponse<String> updatePlatformDetail(@RequestBody String platforms, HttpServletRequest request){
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ")+1);
        User u = JwtUtil.unsign(jwt,User.class);
/*        if(!jwt.equals(redisUtil.get(u.getId()+""))){
            return ServerResponse.createByAuthMsg("该账号已经在别处登录！");
        }*/
        if(u == null){
            return ServerResponse.createByErrorMsg("token无效");
        }
        try{
            List<Platform> platforms1 = JSONObject.parseArray(platforms, Platform.class);
            platformService.updatePlatformDetail(platforms1);
            return ServerResponse.createBySuccessMsg("修改成功！");
        }catch (Exception e){
            e.printStackTrace();
            return ServerResponse.createByACCOUNTError("修改失败！");
        }
    }
}
